<template>
	<div class="wrapper">
		<header>
			<div class="back-btn" @click="goBack">
				<i class="fa fa-arrow-left"></i>
			</div>
			<h3>商户管理</h3>
		</header>

		<div class="search">
			<div class="search-fixed-top" id="fixedBox">
				<div class="search-box">
					<i class="fa fa-search"></i>
					<p>搜索商家名称或商家ID</p>
				</div>
			</div>
		</div>

		<div class="business-list">
			<div class="list-title">
				<i class="fa fa-list-alt"></i>
				<p>商家列表</p>
			</div>

			<ul class="business-items">
				<li v-for="(business, index) in businesses" :key="business.id || index">
					<img :src="getImagePath(business.image)">
					<div class="business-info">
						<div class="business-info-left">
							<h2>{{ business.name }}</h2>
							<h3>{{ business.address }}</h3>
							<p :class="['status-text', business.approved ? 'status-approved' : 'status-pending']">
								{{ business.approved ? '注册状态：批准' : '注册状态：未批准' }}
							</p>
						</div>
						<div class="status-toggle">
							<button :class="['toggle-btn', business.approved ? 'approved' : 'pending']"
								@click="toggleStatus(index)">{{ business.approved ? '取消批准' : '批准' }}
							</button>
						</div>
					</div>
				</li>
				<li v-if="!loading && businesses.length === 0" style="text-align:center;color:#888;padding:3vw 0;">
					暂无数据
				</li>
			</ul>
		</div>
	</div>

</template>

<script>

export default {
	data() {
		return {
			// 改为真实数据
			businesses: [],
			loading: false,
			err: '',
			// 修复滚动定位相关变量
			fixedBox: null,
			searchBox: null,
			originalStyles: {
				width: '',
				marginLeft: ''
			},
			// 保存原始位置信息
			originalPosition: { left: 0 }
		}
	},
	methods: {
		goBack() {
			this.$router.go(-1);
		},
		getImagePath(imageName) {
			if (!imageName) { try { return require('@/assets/friedrice.png') } catch { return '' } }
			if (/^https?:\/\//i.test(imageName)) return imageName
			try { return require(`@/assets/${imageName}`) } catch { return imageName }
		},
		// 切换特定商家的状态
		isApproved(remark) {
			const r = String(remark || '')
			return r.includes('审核通过') || r.includes('审核成功')
		},

		async getUserAuthorities(ownerId) {
			const http = this.$axios || window.axios
			const res = await http.get('/user')
			const arr = Array.isArray(res?.data?.data) ? res.data.data : (Array.isArray(res?.data) ? res.data : [])
			const u = (arr || []).find(x => String(x.id) === String(ownerId))
			const list = (u?.authorities || u?.roles || []).map(a => a.name || a)
			return Array.from(new Set([...(list || []), 'USER']))
		},

		// 用 PATCH /user 覆盖写回权限
		async setUserAuthorities(ownerId, names) {
			const http = this.$axios || window.axios
			const authorities = Array.from(new Set(names)).map(name => ({ name }))
			// 如果你的 axios 已配置 baseURL='/api'，把下面路径改回 '/user'
			await http.patch('/user', { id: ownerId, authorities })
		},

		async grantBusinessRole(ownerId) {
			if (!ownerId) return
			const names = await this.getUserAuthorities(ownerId)
			if (!names.includes('BUSINESS')) names.push('BUSINESS')
			await this.setUserAuthorities(ownerId, names)
		},

		async toggleStatus(index) {
			const row = this.businesses[index]
			if (!row?.id) return alert('缺少商家ID')
			const nextApproved = !row.approved
			const remark = nextApproved ? '审核通过' : ''

			const http = this.$axios || window.axios
			try {
				// 关键：用 remark（单数）
				await http.patch(`/businesses/${row.id}`, { remarks: remark })
				this.businesses[index].approved = nextApproved
				this.businesses[index].remark = remark

				if (nextApproved) await this.grantBusinessRole(row.ownerId)
			} catch (e) {
				console.error('审核更新失败', e?.response || e)
				alert(e?.response?.data?.message || '更新失败，请稍后重试')
			}
		},
		async load() {
			this.loading = true; this.err = ''
			const http = this.$axios || window.axios
			try {
				// 拉全量，包含待审核
				const res = await http.get('/businesses/public')
				const arr = Array.isArray(res?.data?.data) ? res.data.data : (Array.isArray(res?.data) ? res.data : [])
				this.businesses = (arr || []).map(b => ({
					id: b.id || b.businessId,
					name: b.businessName || b.name || `商家#${b.id ?? ''}`,
					address: b.businessAddress || b.address || '',
					image: b.businessImg || b.image || '',
					remark: b.remark ?? b.remarks ?? '',
					approved: ['审核通过', '审核成功'].some(k => String(b.remark ?? b.remarks ?? '').includes(k)),
					ownerId: b.businessOwnerId
				}))
			} catch (e) {
				console.error('加载失败', e?.response || e)
				this.err = e?.response?.data?.message || '加载失败，请稍后重试'
				this.businesses = []
			} finally { this.loading = false }
		},
		// 初始化滚动处理
		initScrollHandler() {
			this.fixedBox = document.getElementById('fixedBox');
			this.searchBox = document.querySelector('.search-box');

			this.originalStyles = {
				width: window.getComputedStyle(this.searchBox).width,
				position: window.getComputedStyle(this.searchBox).position,
				left: window.getComputedStyle(this.searchBox).left,
				transform: window.getComputedStyle(this.searchBox).transform,
				marginLeft: window.getComputedStyle(this.searchBox).marginLeft,
				top: window.getComputedStyle(this.searchBox).top
			};

			window.addEventListener('scroll', this.handleScroll);
			window.addEventListener('resize', this.handleResize);
		},
		// 处理滚动事件
		handleScroll() {
			let s1 = document.documentElement.scrollTop;
			let s2 = document.body.scrollTop;
			let scroll = s1 === 0 ? s2 : s1;
			let width = document.documentElement.clientWidth;

			if (scroll > width * 0.12) {
				this.fixedBox.classList.add('fixed');
				this.searchBox.style.width = '90%';
				this.searchBox.style.position = 'fixed';
				this.searchBox.style.left = '50%';
				this.searchBox.style.transform = 'translateX(-50%)';
				this.searchBox.style.top = '1vw';
				this.searchBox.style.marginLeft = '0';

				document.querySelector('.search').style.height = this.fixedBox.offsetHeight + 'px';
			} else {
				this.fixedBox.classList.remove('fixed');
				this.searchBox.style.width = '';
				this.searchBox.style.position = '';
				this.searchBox.style.left = '';
				this.searchBox.style.transform = '';
				this.searchBox.style.top = '';
				this.searchBox.style.marginLeft = '';
				this.searchBox.offsetHeight;
				document.querySelector('.search').style.height = '';
			}
		},

		// 处理窗口大小变化
		handleResize() {
			if (this.fixedBox.classList.contains('fixed')) {
				this.searchBox.style.left = '50%';
				this.searchBox.style.transform = 'translateX(-50%)';
			}
		},
	},

	mounted() {
		this.$nextTick(() => {
			this.initScrollHandler();
			this.load();
		});
	},
	beforeUnmount() {
		window.removeEventListener('scroll', this.handleScroll);
		window.removeEventListener('resize', this.handleResize);
	}
}
</script>

<style>
.wrapper {
	width: 100%;
	height: 100%;
	background-color: #FFFFFF;
}

.wrapper header {
	width: 100%;
	height: 15vw;
	background-color: #0097FF;
	display: flex;
	align-items: center;
	user-select: none;
}

.wrapper header .back-btn {
	color: #FFFFFF;
	font-size: 6vw;
	margin-left: 2.5vw;
	cursor: pointer;
	display: flex;
	align-items: center;
	justify-content: center;
	width: 8vw;
	height: 8vw;
}

.wrapper header h3 {
	font-size: 6vw;
	font-weight: 700;
	color: #FFFFFF;
	margin-left: 2.5vw;
	font-family: "宋体";
}


.wrapper .search {
	width: 100%;
	height: 8vw;
	background-color: #FFFFFF;
	position: relative;
	transition: height 0.3s ease;
}

.wrapper .search-fixed-top {
	width: 100%;
	transition: all 0.3s ease;
}

.wrapper .search-fixed-top.fixed {
	position: fixed;
	top: 0;
	left: 0;
	z-index: 100;
	background: white;
	box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
	padding: 1vw 0;
	display: flex;
	justify-content: center;
}

.wrapper .search .search-fixed-top .search-box {
	width: 90%;
	height: 6vw;
	background-color: #F5F5F5;
	display: flex;
	margin-left: 5%;
	margin-top: 1vw;
	justify-content: center;
	align-items: center;
	user-select: none;
	border-radius: 3vw;
}

.wrapper .search .search-fixed-top.fixed .search-box {
	position: relative;
}

.wrapper .search .search-fixed-top .search-box .fa-search {
	font-size: 3vw;
}

.wrapper .search .search-fixed-top .search-box p {
	font-size: 2.8vw;
	margin-left: 1.5vw;
}

.wrapper .business-list {
	width: 100%;
	padding-bottom: 5vw;
}

.wrapper .business-list .list-title {
	width: 90%;
	height: 8vw;
	background-color: #0097FF;
	display: flex;
	user-select: none;
	margin-left: 5%;
	margin: 2vw auto;
	border-radius: 4px;
	align-items: center;
}

.wrapper .business-list .list-title .fa-list-alt {
	font-size: 3.5vw;
	color: #FFFFFF;
	margin-left: 4vw;
}

.wrapper .business-list .list-title p {
	font-size: 3.5vw;
	margin-left: 2vw;
	color: #FFFFFF;
	font-weight: 500;
}

.wrapper .business-items {
	width: 90%;
	margin: 0 auto;
	list-style: none;
	padding: 0;
}

.wrapper .business-items li {
	width: 100%;
	box-sizing: border-box;
	padding: 3vw;
	user-select: none;
	border-top: solid 0.5px #DDD;
	border-bottom: solid 0.5px #DDD;
	display: flex;
	background-color: #FFFFFF;
	margin-bottom: 2vw;
	border-radius: 8px;
	box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
}

.wrapper .business-items li img {
	width: 18vw;
	height: 18vw;
	border-radius: 8px;
	object-fit: cover;
}

.wrapper .business-items li .business-info {
	flex: 1;
	display: flex;
	justify-content: space-between;
	padding-left: 3vw;
}

.wrapper .business-items li .business-info .business-info-left h2 {
	font-size: 4vw;
	color: #000000;
	margin-bottom: 1vw;
	font-weight: 700;
}

.wrapper .business-items li .business-info .business-info-left h3 {
	font-size: 3.2vw;
	color: #666;
	margin-bottom: 2vw;
	font-weight: 400;
}

/* 状态文本样式 */
.wrapper .business-items li .business-info .business-info-left p {
	font-size: 3.2vw;
	font-weight: 500;
	transition: color 0.3s ease;
}

/* 未批准状态样式 */
.status-pending {
	color: #FF0000;
}

/* 批准状态样式 */
.status-approved {
	color: #0097FF;
}

/* 状态切换区域样式 */
.status-toggle {
	display: flex;
	align-items: center;
	justify-content: center;
}

/* 切换按钮样式 */
.toggle-btn {
	width: 20vw;
	height: 8vw;
	background-color: #0097FF;
	color: white;
	border: none;
	border-radius: 4vw;
	font-size: 3vw;
	display: flex;
	align-items: center;
	justify-content: center;
	cursor: pointer;
	transition: background-color 0.3s ease;
	padding: 0 3vw;
}

/* 未批准状态按钮样式 */
.toggle-btn.pending {
	background-color: #FF3B30;
}

/* 批准状态按钮样式 */
.toggle-btn.approved {
	background-color: #4CD964;
}

/* 媒体查询适配小屏幕 */
@media (max-width: 480px) {
	.wrapper .search .search-fixed-top .search-box {
		width: 92%;
		margin-left: 4%;
	}

	.wrapper .search-fixed-top.fixed .search-box {
		width: 92% !important;
	}
}
</style>